#include <stdio.h>
#include <string.h>

#include "stm32f10x.h"
#include "stm32f10x_conf.h"
#include "bcd100.h"
#include "delay.h"
#include "serial.h"

int BCD100_Configuration(GPIO_TypeDef* reset_GPIO, int reset_pin)
{
  /* reset module during 20ms and wait some after reset */
  GPIO_ResetBits(reset_GPIO, reset_pin);
  udelay(20000);
  GPIO_SetBits(reset_GPIO, reset_pin);
  udelay(20000);

  if(!BCD100_Command("AT"))
    return 0;
  
  /* hardware restart */
  if(!BCD100_Command("AT&F"))
    return 0;
  
  /* mode=3 for waiting connection from any device */
  if(!BCD100_Command("AT+BTMODE,3"))
    return 0;
  
  /* uartconfig 9600 without hardware handshaking */
  if(!BCD100_Command("AT+UARTCONFIG, 9600,n,1,0"))
    return 0;
  
  /* no authentication, no encryption */
  if(!BCD100_Command("AT+BTSEC,1,0"))
    return 0;

  /* set name of device */
  if(!BCD100_Command("AT+BTNAME=TANK32"))
    return 0;
  
  /* soft restart to apply configuration */
  if(!BCD100_Command("ATZ"))
    return 0;
  
  return 1;
}

//#define BCD100_CHECK_ANSWER

int BCD100_Command(const char *command)
{
  char answer[50];
  
  Serial_Clear();
  putstring(command, serial1);
  putchar('\r');
  putchar('\n');
  gets_trim(answer);
  
#ifdef BCD100_CHECK_ANSWER
  if (strcmp(answer, "OK") != 0)
    return 0;
#else
  mdelay(50);
#endif
  
  return 1;
}
